package com.dyzx.hbb.modules.sys.controller;

import cn.hutool.core.bean.BeanUtil;
import com.dyzx.hbb.common.base.Result;
import com.dyzx.hbb.common.config.MyLambdaQueryWrapper;
import com.dyzx.hbb.common.controller.BaseValidController;
import com.dyzx.hbb.common.utils.Utils;
import com.dyzx.hbb.modules.sys.entity.SysWorkDiscount;
import com.dyzx.hbb.modules.sys.entity.SysWorkDiscountTask;
import com.dyzx.hbb.modules.sys.entity.SysWorkPayment;
import com.dyzx.hbb.modules.sys.query.SysWorkDiscountQuery;
import com.dyzx.hbb.modules.sys.service.SysWorkDiscountService;
import com.dyzx.hbb.modules.sys.service.SysWorkDiscountTaskService;
import com.dyzx.hbb.modules.sys.service.SysWorkPaymentService;
import com.dyzx.hbb.modules.sys.vo.SysWorkDiscountTaskVO;
import com.dyzx.hbb.modules.sys.vo.SysWorkDiscountUVO;
import com.dyzx.hbb.modules.sys.vo.SysWorkDiscountVO;
import com.dyzx.hbb.security.context.SecurityContextHolder;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/sys/discount")
@RestController
@Tag(name = "12.优惠管理", description = "优惠相关接口")
public class SysDiscountController extends BaseValidController<SysWorkDiscountService, SysWorkDiscount, SysWorkDiscountQuery, SysWorkDiscountVO, SysWorkDiscountUVO> {

    @Autowired
    private SysWorkDiscountService service;

    @Autowired
    private SysWorkDiscountTaskService taskService;

    @Autowired
    private SysWorkPaymentService paymentService;

    @Override
    protected SysWorkDiscountService getBaseService() {
        return service;
    }

    @Override
    protected SysWorkDiscount addValid(SysWorkDiscountVO entity) {
        Long organId = SecurityContextHolder.getOrganId();
        MyLambdaQueryWrapper<SysWorkDiscount> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(SysWorkDiscount::getOrganId, organId);
        long count = service.count(queryWrapper);
        String no = Utils.generateYMOrderNumber("SD" + organId, count);


        SysWorkDiscount data = new SysWorkDiscount();
        BeanUtil.copyProperties(entity, data);
        data.setNo(no);

        return data;
    }

    @Override
    protected SysWorkDiscount editValid(SysWorkDiscountUVO entity) {
        return null;
    }

    @Override
    protected MyLambdaQueryWrapper<SysWorkDiscount> queryWrapper(SysWorkDiscountQuery query) {
        MyLambdaQueryWrapper<SysWorkDiscount> wrapper = new MyLambdaQueryWrapper<>();

        wrapper.select(SysWorkDiscount::getId, SysWorkDiscount::getNo, SysWorkDiscount::getName, SysWorkDiscount::getType, SysWorkDiscount::getAmt, SysWorkDiscount::getCustomerId, SysWorkDiscount::getApprovedUserId, SysWorkDiscount::getApprovedDate, SysWorkDiscount::getStatus, SysWorkDiscount::getCreateDate, SysWorkDiscount::getUpdateDate, SysWorkDiscount::getDeleted, SysWorkDiscount::getOperatorId, SysWorkDiscount::getOrganId, SysWorkDiscount::getTargetId, SysWorkDiscount::getTargetType, SysWorkDiscount::getOrderId, SysWorkDiscount::getStartDate, SysWorkDiscount::getEndDate);

        if (query != null) {

//name, no, type, status, target_id, target_type
            wrapper.like(StringUtils.isNotBlank(query.getName()), SysWorkDiscount::getName, query.getName())
                    .like(StringUtils.isNotBlank(query.getNo()), SysWorkDiscount::getNo, query.getNo())
                    .eq(query.getType() != null, SysWorkDiscount::getType, query.getType())
                    .eq(query.getTarget_id() != null, SysWorkDiscount::getTargetId, query.getTarget_id())
                    .eq(query.getTarget_type() != null, SysWorkDiscount::getTargetType, query.getTarget_type())
                    .eq(query.getStatus() != null, SysWorkDiscount::getStatus, query.getStatus());


        }
        return wrapper;

    }

    @Override
    protected MyLambdaQueryWrapper<SysWorkDiscount> queryInfoWrapper() {
        MyLambdaQueryWrapper<SysWorkDiscount> wrapper = new MyLambdaQueryWrapper<>();
        wrapper.select(SysWorkDiscount::getId, SysWorkDiscount::getNo, SysWorkDiscount::getName, SysWorkDiscount::getType, SysWorkDiscount::getAmt, SysWorkDiscount::getCustomerId, SysWorkDiscount::getApprovedUserId, SysWorkDiscount::getApprovedDate, SysWorkDiscount::getStatus, SysWorkDiscount::getCreateDate, SysWorkDiscount::getUpdateDate, SysWorkDiscount::getDeleted, SysWorkDiscount::getOperatorId, SysWorkDiscount::getOrganId, SysWorkDiscount::getTargetId, SysWorkDiscount::getTargetType, SysWorkDiscount::getOrderId, SysWorkDiscount::getStartDate, SysWorkDiscount::getEndDate);

        wrapper.userName(SysWorkDiscount::getOperatorId).as("operator_name");
        wrapper.userName(SysWorkDiscount::getApprovedUserId).as("approved_user_name");
        wrapper.userName(SysWorkDiscount::getCustomerId).as("customer_name");
        return wrapper;
    }

    //处理 PUT /sys/discount/status
    @Operation(summary = "修改状态", description = "修改状态")
    @PutMapping("/status/{id}")
    public Result<Boolean> updateStatus(@PathVariable Long id, @RequestParam Integer status) {
        SysWorkDiscount sysWorkDiscount = service.getById(id);
        Long userId = SecurityContextHolder.getUserId();
        if (sysWorkDiscount == null) {
            return Result.error("优惠记录不存在");
        }
        sysWorkDiscount.setApprovedUserId(userId);
        sysWorkDiscount.setStatus(status);
        if (status == 1) {
            sysWorkDiscount.setApprovedDate(System.currentTimeMillis());
        }
        return service.updateById(sysWorkDiscount) ? Result.ok() : Result.error();
    }

    /// sys/discount/my/$orderId/$workId
    @Operation(summary = "我的优惠", description = "我的优惠")
    @GetMapping("/coupon/{orderId}/{workId}")
    public Result<List<SysWorkDiscount>> my(@PathVariable Long orderId, @PathVariable Long workId) {
        Long organId = SecurityContextHolder.getOrganId();
        Long userId = SecurityContextHolder.getUserId();
        MyLambdaQueryWrapper<SysWorkDiscount> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(SysWorkDiscount::getOrganId, organId);
        queryWrapper.eq(SysWorkDiscount::getStatus, 1);
      /*  queryWrapper.eq(SysWorkDiscount::getOrderId, orderId);
        queryWrapper.eq(SysWorkDiscount::getTargetId, workId);*/

        // order_id or work_id
        if (orderId != null && workId != null) {
            queryWrapper.eq(SysWorkDiscount::getOrderId, orderId).eq(SysWorkDiscount::getWorkId, workId);

        } else if (orderId == null && workId != null) {
            queryWrapper.eq(SysWorkDiscount::getWorkId, workId);
            queryWrapper.isNull(SysWorkDiscount::getOrderId);
        } else {
            return Result.ok(List.of());
        }
        long endDate = System.currentTimeMillis();
        queryWrapper.le(SysWorkDiscount::getStartDate, endDate);
        queryWrapper.ge(SysWorkDiscount::getEndDate, endDate);


        List<SysWorkDiscount> list = service.list(queryWrapper);
        return Result.ok(list);
    }
    // PUT /sys/discount/approval/$id
    @Operation(summary = "审批优惠", description = "审批优惠")
    @PutMapping("/approval/{id}")
    public Result<Boolean> approval(@PathVariable Long id, @RequestParam Integer status) {
        SysWorkDiscount sysWorkDiscount = service.getById(id);
        Long userId = SecurityContextHolder.getUserId();
        if (sysWorkDiscount == null) {
            return Result.error("优惠记录不存在");
        }
        sysWorkDiscount.setApprovedUserId(userId);
        sysWorkDiscount.setStatus(status);
        if (status == 1) {
            sysWorkDiscount.setApprovedDate(System.currentTimeMillis());
        }
        return service.updateById(sysWorkDiscount) ? Result.ok() : Result.error();
    }
    // PUT /sys/discount/task/$id  work_id,order_id
    @Operation(summary = "任务优惠", description = "任务优惠")
    @PutMapping("/task/{id}")
    public Result<Boolean> task(@PathVariable Long id,@RequestBody SysWorkDiscountTaskVO data) {
    Long workId = data.getWorkId();
    Long orderId = data.getOrderId();

        SysWorkDiscount sysWorkDiscount = service.getById(id);
        Long userId = SecurityContextHolder.getUserId();
        if (sysWorkDiscount == null) {
            return Result.error("优惠记录不存在");
        }
       sysWorkDiscount.setStatus(4);
        boolean b = service.updateById(sysWorkDiscount);
        if(b){
            SysWorkDiscountTask sysWorkDiscountTask = new SysWorkDiscountTask();
            sysWorkDiscountTask.setDiscountId(id);
            sysWorkDiscountTask.setWorkId(workId);
            sysWorkDiscountTask.setOrderId(orderId);
            sysWorkDiscountTask.setCreateDate(System.currentTimeMillis());
            sysWorkDiscountTask.setUpdateDate(System.currentTimeMillis());
            sysWorkDiscountTask.setOperatorId(userId);
            sysWorkDiscountTask.setOrganId(SecurityContextHolder.getOrganId());
            boolean save = taskService.save(sysWorkDiscountTask);
            if ( save){
           boolean b1    = paymentService.updateWorkItemDiscount(workId,orderId,data.getItemId(),id,sysWorkDiscount.getAmt());
            }
        }
        return b ? Result.ok() : Result.error();
    }
}
